<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRolesDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdBottom', index1 === 0 ? 'bdTop' : '', 'center']"
                    v-for="(item1, index1) in scope.row.children"
                    :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 渲染二级权限 -->
                <el-row :class="[index2 === 0 ? '' : 'bdTop', 'center']"
                        v-for="(item2, index2) in item1.children"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success"
                            closable
                            @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 通过for循环 嵌套渲染三级权限 -->
                    <el-tag v-for="(item3) in item2.children"
                            :key="item3.id"
                            type="warning"
                            closable
                            @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
              <el-button size="mini"
                         type="primary"
                         icon="el-icon-edit"
                         @click="showEditDialog(scope.row.id)">编辑</el-button>
              <el-button size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="removeRoles(scope.row.id)">删除</el-button>
              <el-button size="mini"
                         type="warning"
                         icon="el-icon-setting"
                         @click="showRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialog"
      width="50%">
      <el-form :rules="roleRules"
               ref="addRolesRef"
               :model="addRoles" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoles.roleName">{{addRoles.roleName}}</el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoleNews">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialog"
      width="50%">
      <el-form :model="editRoles"
               :rules="roleRules"
               ref="editRolesRef"
               label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="changeRolesNews">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialog"
      width="50%"
      @close="setRightsDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightsList"
               :props="treeProps"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-checked-keys="defKeys"
               ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  data() {
    return {
      //所有角色列表数据
      rolesList: [],
      //控制分配权限对话框显示与隐藏
      setRightsDialog:false,
      //所有权限的数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中的节点id值数组
      defKeys: [],
      //当前即将分配权限的id
      roleId: '',
      //控制添加角色对话框显示与隐藏
      addRolesDialog: false,
      //需要传递的参数列表
      addRoles: {
        roleName: '',
        roleDesc: ''
      },
      //添加用户验证规则
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      //控制修改用户对话框的显示与隐藏
      editRolesDialog: false,
      //查询到的角色信息
      editRoles: {}
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    //获取所有角色的列表
    async getRoles() {
      const {data: res} = await this.$http.get('roles')
      if(res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList);
    },
    //根据id删除对应的权限
    async removeRightById(role, rightId) {
      //弹框提示是否删除
      const confirmResult = await this.$confirm('确定删除此用户的该权限吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if(confirmResult !== 'confirm') {
        return this.$message.info('取消了删除操作')
      }
      const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if(res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      //重新刷新权限列表
      // this.getRoles()
      role.children = res.data
    },
    //展示分配权限的对话框
    async showRightsDialog(role) {
      this.roleId = role.id

      const{data: res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      //把获取的权限数据保存到data中
      this.rightsList = res.data
      console.log(role);
      //获取所有三级权限的id
      this.getThreeKeys(role, this.defKeys)

      this.setRightsDialog = true
    },
    //通过递归的方式，获取所有角色下三级权限的id
    getThreeKeys(node, arr) {
      //如果当前node不包含children则表示是三级权限
      if(!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getThreeKeys(item, arr)
      });
    },
    //监听分配权限的关闭事件
    setRightsDialogClosed() {
      this.defKeys = []
    },
    //点击确定为角色分配权限
    async addRight() {
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keyStr = key.join(',')
      //发送请求
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: keyStr
      })

      if(res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoles()
      //隐藏对话框
      this.setRightsDialog = false
    },
    //点击添加角色按钮显示对话框
    showAddRolesDialog() {
      this.addRolesDialog = true
    },
    //点击确定按钮添加角色
    addRoleNews() {
      this.$refs.addRolesRef.validate(async valid => {
        if(!valid) {
          return
        }
        const {data: res} = await this.$http.post('roles', this.addRoles)
        if(res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.addRolesDialog = false
        this.getRoles()
      })
    },
    //点击编辑显示对应id的角色
    async showEditDialog(id) {
      const {data: res} = await this.$http.get('roles/' + id)
      if(res.meta.status !== 200) {
        return this.$message.error('查询角色失败')
      }
      this.editRoles = res.data
      this.editRolesDialog = true
    },
    //根据id对角色信息进行就该
    changeRolesNews() {
      this.$refs.editRolesRef.validate(async valid => {
        if(!valid) {
          return
        }
        //发起修改角色请求
        const {data: res} = await this.$http.put('roles/' + this.editRoles.roleId, {
          roleName: this.editRoles.roleName,
          roleDesc: this.editRoles.roleDesc
        })
        if(res.meta.status !== 200) {
          return this.$message.error('修改角色失败')
        }
        this.editRolesDialog = false
        this.getRoles()
        this.$message.success('修改角色成功')
      })
    },
    //根据id删除对应角色
    async removeRoles(id) {
      const confirmResult = await this.$confirm('是否确认删除此角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(confirmResult !== 'confirm') {
        return this.$message.info('取消删除该角色')
      }
      const {data: res} = await this.$http.delete('roles/' + id)
      if(res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRoles()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.center {
  display: flex;
  align-items: center;
}
</style>
